from flask import Flask,request
from flask_pymongo import PyMongo
from flask import make_response,send_file
from wordcloud import WordCloud
import socket

host = "localhost"

port = "8080"
host_port = host+":"+port+"/"
word_cloud = WordCloud(font_path='msyh.ttc', height=400, width = 300, background_color='white', scale = 3 )
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://"+host+":27017/eye-trace"
mongo = PyMongo(app)
from elasticsearch import Elasticsearch
client = Elasticsearch([{'host':host}])

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route("/get_last_user_id")
def get_last_user_id():
    last_user = mongo.db.temp.find_one({"_id":"last_user"})
    return last_user

@app.route("/recommend")
def recommend_api():
    user_id = request.args.to_dict().get("user_id")
    response = recommend(user_id)
    return response

def recommend(user_id):
    TOPN = 20
    top_n_keywords_list = find_top_n_words(user_id,TOPN)
    body = get_empty_body()
    for keyword_value in top_n_keywords_list:
        keyword = keyword_value[0]
        boost = keyword_value[1]
        match = get_match("movie_comments",keyword,boost)
        body['query']['bool']['should'].append(match)
    response =client.search(index = "douban2.0",body = body)
    return response


def get_empty_body():
    body = {
       "query" : {
                "bool" : {
                  "should" : [
                  ]
               }
       },
        #"_source": ["movie_cover"]
         "_source":["movie_name","movie_info","movie_cover","movie_profile","movie_score","movie_score_amount","movie_short_profile"]
    }
    return body

def get_match(meta,keyword,boost):
    match = {
        "match" : {
            meta : {
                "query":keyword,
                "boost":boost
                 }
        }
    }
    return match

def find_top_n_words(user_id,top_n):
    user_data = mongo.db.user.find_one({"_id":user_id})
    d = user_data['keywords']
    sorted_keywords = sorted(d.items(), key=lambda d:d[1], reverse=True)
    return sorted_keywords[:top_n]

@app.route("/wordcloud")
def wordcloud_api():
    user_id = request.args.to_dict().get("user_id")
    response = {}
    response['0']={"_id": "keywords", "url":wordcloud_keywords(user_id)}
    response['1']={"_id": "movies", "url":wordcloud_movies(user_id)}
    return response

def wordcloud_keywords(user_id):
    user_data = mongo.db.user.find_one({"_id": user_id})
    frequencies = user_data['keywords']
    word_cloud.generate_from_frequencies(frequencies)
    pic_path = "static/"+user_data['_id']+"_keywords.jpg"
    word_cloud.to_file(pic_path)
    return host_port+pic_path

def wordcloud_movies(user_id):
    user_recommend = recommend(user_id)
    frequencies = {}
    for movie in user_recommend['hits']['hits']:
        movie_name = movie['_source']['movie_name']
        movie_score = movie['_score']
        frequencies[movie_name] = int(movie_score)
    word_cloud.generate_from_frequencies(frequencies)
    pic_path = "static/"+user_id+"_movie.jpg"
    word_cloud.to_file(pic_path)
    return host_port+pic_path


if __name__ == '__main__':
    app.run(host='0.0.0.0',port=port)
